var createError = require('http-errors');
var http = require('http');
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
const sessionConfig = require('./config/session.config')
var logger = require('morgan');
const UserRouters = require('./routes/UserRouters')
const NewsRouters = require('./routes/NewsRouters')
const CommentsRouters = require('./routes/CommentRouters')
const { addPrefixToRoutes }  = require('./utils/index')
const mongoConnect = require('./config/db.config')
const { API_PREFIX } = require('./config/index')
var app = express();
// 连接数据库
mongoConnect()
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// addPrefixToRoutes(app)
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.use(cookieParser());
app.use(sessionConfig())
//post请求不能直接获取参数
app.use(bodyParser.json({ limit: '1mb'}))//body-parser 解析json格式数据
app.use(bodyParser.urlencoded({ extended: true}))
app.all('*', function (req, res, next) {
  const origin =  req.headers['origin']
  res.header("Access-Control-Allow-Origin", origin);
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By", ' 3.2.1');
  res.header('Access-Control-Allow-Credentials',"true");
  res.header("Content-Type", "application/json;charset=utf-8");
  if (req.method === "OPTIONS") {
    res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
    res.send(200);
  }
  else {
    next();
  }
})
app.use(express.static(path.join(__dirname, 'public')));

addPrefixToRoutes(app)
app.use(API_PREFIX,UserRouters)
app.use(API_PREFIX,NewsRouters)
app.use(API_PREFIX,CommentsRouters)
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});
/**
 * Create HTTP server.
 */

var server = http.createServer(app);


/**
 * Listen on provided port, on all network interfaces.
 */

server.listen(5001);

module.exports = app;
